<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="请选择将要提交的节点并选择节点上的用户"
    @ok="handleSuccess"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { schemas } from './transmitModal.data';
  import { getFlowSubmitTo, getFlowGetActions } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  export default defineComponent({
    components: { BasicModal, BasicForm },
    emits: ['success'],
    setup(_, { emit }) {
      const modelRef = ref<Recordable>({});
      const [
        registerForm,
        {
          resetFields,
          validate,
          updateSchema,
          // setFieldsValue,
          // setProps
        },
      ] = useForm({
        labelWidth: 100,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [register, { closeModal }] = useModalInner((data) => {
        data && fetch(data);
      });

      const typeCode = ref('');
      const flowId = ref('');
      async function fetch(data) {
        typeCode.value = data?.typeCode;
        flowId.value = data?.flowId;
        modelRef.value = data?.record;
        await nextTick();
        resetFields();
        getFlowUsers();
      }

      const getFlowUsers = async () => {
        if (!unref(flowId)) {
          return;
        }
        const data = await getFlowGetActions({ flowId: unref(flowId) });
        if (isArray(data)) {
          const newData = data.map((item) => {
            return {
              label: `${item.jobName}:${item.title}`,
              value: item.internalName,
            };
          });
          updateSchema([
            {
              field: 'internalName',
              componentProps: {
                options: newData,
                getPopupContainer: () => document.body,
              },
            },
          ]);
        }
      };

      const handleSuccess = async () => {
        try {
          const values = await validate();
          let formata = Object.assign({}, values);
          formata.flowId = unref(flowId);
          formata.myActionId = unref(modelRef).id;
          await getFlowSubmitTo(formata);
          closeModal();
          emit('success', formata);
        } catch (err) {
          console.log(err);
        } finally {
        }
      };
      return { register, schemas, registerForm, model: modelRef, handleSuccess };
    },
  });
</script>
